package xyhoo.springframework.util;

import java.net.*;

public abstract class ResourceUtils {

    public static final String CLASSPATH_URL_PREFIX = "classpath:";

    public static void useCacheIfNecessary(URLConnection con) {
        con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
    }

    public static boolean isUrl(String resourceLocation) {
        if (resourceLocation == null) {
            return false;
        }
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            return true;
        }
        try {
            toURL(resourceLocation);
            return true;
        }
        catch (MalformedURLException ex) {
            return false;
        }
    }

    public static URL toURL(String location) throws MalformedURLException {
        // Equivalent without java.net.URL constructor - for building on JDK 20+
		/*
		try {
			return toURI(StringUtils.cleanPath(location)).toURL();
		}
		catch (URISyntaxException | IllegalArgumentException ex) {
			MalformedURLException exToThrow = new MalformedURLException(ex.getMessage());
			exToThrow.initCause(ex);
			throw exToThrow;
		}
		*/

        return new URL(location);
    }

    public static URI toURI(String location) throws URISyntaxException {
        return new URI(StringUtils.replace(location, " ", "%20"));
    }
}
